/**
 * 智能分析模块 - 对象中心化版本 + 侧边栏导航布局
 */
console.log('[Analysis] 正在加载智能分析模块...');

// 全局状态
let currentSubject = null; // 当前选中的分析对象
let allSubjects = []; // 所有人员列表
let currentResults = null; // 当前分析结果缓存
let activeView = 'overview'; // 当前视图: 'overview' 或 analyzer.id

// 分析器配置定义
const ANALYZER_GROUPS = [
    {
        id: 'financial',
        title: '资金战法',
        icon: '💰',
        analyzers: [
            { id: 'fast_pass', name: '快进快出', class: 'FastPassAnalyzer', params: { timeWindowHours: 2, minAmount: 50000 } },
            { id: 'smurfing', name: '蚂蚁搬家', class: 'SmurfingAnalyzer', params: { timeWindowDays: 7, minTotalAmount: 100000 } },
            { id: 'off_hour', name: '异常时间交易', class: 'OffHourTradingAnalyzer', params: { offHourStart: 22, offHourEnd: 6, minAmount: 50000 } },
            { id: 'special_amount', name: '特定金额筛查', class: 'SpecialAmountAnalyzer', params: { targetAmounts: [50000, 100000, 200000] } },
            { id: 'loop', name: '资金回流', class: 'LoopAnalyzer', params: { minAmount: 10000, timeWindowDays: 30 } },
            { id: 'dormant', name: '休眠账户激活', class: 'DormantAnalyzer', params: { dormantMonths: 6, minAmount: 50000 } }
        ]
    },
    {
        id: 'communication',
        title: '通讯战法',
        icon: '📞',
        analyzers: [
            { id: 'intimacy', name: '特殊时段通联', class: 'IntimacyAnalyzer', params: { nightStart: 22, nightEnd: 6, minCalls: 3 } },
            { id: 'single_contact', name: '单线联系人', class: 'SingleContactAnalyzer', params: { minCalls: 5 } },
            { id: 'sim_swap', name: '断卡行动', class: 'SimSwapAnalyzer', params: { maxDays: 7 } },
            { id: 'event_corr', name: '关键事件伴随', class: 'EventCorrelationAnalyzer', params: {} }
        ]
    },
    {
        id: 'geospatial',
        title: '轨迹战法',
        icon: '🗺️',
        analyzers: [
            { id: 'co_travel', name: '同行同住', class: 'CoTravelAnalyzer', params: {} },
            { id: 'hidden_property', name: '隐形房产', class: 'HiddenRealEstateAnalyzer', params: {} },
            { id: 'offline_meeting', name: '线下秘密会面', class: 'OfflineMeetingAnalyzer', params: {} },
            { id: 'nocturnal', name: '昼伏夜出', class: 'NocturnalAnalyzer', params: {} }
        ]
    },
    {
        id: 'correlation',
        title: '综合关联',
        icon: '🔗',
        analyzers: [
            { id: 'shadow_vehicle', name: '隐形车辆', class: 'ShadowVehicleAnalyzer', params: {} },
            { id: 'shadow_shareholder', name: '影子股东', class: 'ShadowShareholderAnalyzer', params: {} },
            { id: 'family_wealth', name: '家庭资产穿透', class: 'FamilyWealthAnalyzer', params: {} },
            { id: 'profile', name: '综合画像', class: 'ComprehensiveProfileAnalyzer', params: {} }
        ]
    }
];

/**
 * 打开智能分析标签页
 */
async function openAnalysisTab() {
    console.log('[Analysis] 打开智能分析页面');

    const tabId = 'analysis-tab';
    let caseId = sessionStorage.getItem('currentCaseId');

    if (!caseId) {
        // 如果没有案件ID，调用全局的案件选择功能
        if (window.selectCase) {
            caseId = await window.selectCase();
            if (!caseId) {
                // 用户取消选择
                console.log('[Analysis] 用户取消选择案件');
                return;
            }
        } else {
            alert('请先选择案件');
            return;
        }
    }

    // 提取人员列表
    try {
        allSubjects = await window.SubjectService.extractSubjectsWithCache(caseId);
    } catch (error) {
        console.error('[Analysis] 提取人员失败:', error);
        allSubjects = [];
    }

    // 重置状态
    currentResults = null;
    activeView = 'overview';

    // 准备侧边栏数据
    const sidebarItems = [
        { type: 'overview', label: '总览仪表盘', icon: '📊', children: [] },
        ...ANALYZER_GROUPS.map(g => ({
            type: g.id,
            label: g.title,
            icon: g.icon,
            children: g.analyzers.map(a => ({
                type: a.id,
                label: a.name,
                icon: '', // 子菜单不显示图标
                id: a.id // 用于徽章查找
            }))
        }))
    ];

    const sidebarHtml = window.SidebarModule.createSidebarHtml(
        'overview',
        'window.AnalysisModule.switchView',
        '智能分析模型',
        sidebarItems,
        'light'
    );

    const contentHtml = `
        <div class="analysis-container" style="display:flex; flex-direction:column; height:100%; width:100%; background-color:#f5f7fa; position:absolute; top:0; left:0; right:0; bottom:0; overflow:hidden;">
            <!-- 顶部栏: 对象选择 -->
            <header style="height:60px; background:white; border-bottom:1px solid #e6e6e6; display:flex; align-items:center; padding:0 20px; flex-shrink:0; justify-content:space-between;">
                <div style="display:flex; align-items:center; gap:15px;">
                    <div style="font-size:18px; font-weight:bold; color:#303133;">🕵️‍♂️ 智能分析</div>
                    <div style="width:1px; height:20px; background:#dcdfe6; margin:0 10px;"></div>
                    <select id="subject-selector" style="width:250px; padding:8px; border:1px solid #dcdfe6; border-radius:4px; font-size:14px;">
                        <option value="">[全量模式] 分析所有数据</option>
                        ${allSubjects.map(s => `
                            <option value="${s.id}">${s.name} ${s.idCard ? '(' + s.idCard.substr(0, 6) + '***)' : ''}</option>
                        `).join('')}
                    </select>
                    <button id="btn-start-analysis" class="btn-primary" style="padding:8px 20px; border-radius:4px; cursor:pointer;">
                        🚀 开始分析
                    </button>
                </div>
                
                <!-- 资产概览小条 -->
                <div id="subject-overview-bar" style="display:none; font-size:13px; color:#606266; background:#f0f9ff; padding:5px 15px; border-radius:15px;">
                    <span style="margin-right:15px;">👤 <strong id="overview-name"></strong></span>
                    <span style="margin-right:15px;">🏦 银行卡: <strong id="overview-bank-count">0</strong></span>
                    <span>📞 手机号: <strong id="overview-phone-count">0</strong></span>
                </div>
            </header>

            <div class="analysis-body" style="flex:1; display:flex; overflow:hidden;">
                <!-- 左侧导航栏 (使用 SidebarModule) -->
                <div id="analysis-sidebar-container" style="height:100%;">
                    ${sidebarHtml}
                </div>

                <!-- 右侧内容区 -->
                <main id="analysis-content-area" style="flex:1; padding:20px; overflow-y:auto; background:#f5f7fa;">
                    <!-- 默认显示空状态或加载中 -->
                    <div id="empty-state" style="height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; color:#909399;">
                        <div style="font-size:64px; margin-bottom:20px; opacity:0.5;">🔍</div>
                        <h3>请选择对象并开始分析</h3>
                        <p>点击上方"开始分析"按钮启动智能研判</p>
                    </div>
                </main>
            </div>
        </div>
    `;

    if (window.createTabInWorkbench) {
        window.createTabInWorkbench(tabId, '智能分析', contentHtml);
    }

    // 绑定事件
    setTimeout(() => {
        setupEventListeners();
        tryLoadLastResult();
    }, 100);
}

/**
 * 切换视图
 */
function switchView(viewId) {
    activeView = viewId;
    renderContent();
    if (window.SidebarModule) {
        const sidebarContainer = document.getElementById('analysis-sidebar-container');
        if (sidebarContainer) {
            window.SidebarModule.updateSelection(sidebarContainer, viewId, 'light');
        }
    }
}

/**
 * 渲染主内容区
 */
function renderContent() {
    const container = document.getElementById('analysis-content-area');

    if (!currentResults) {
        // 保持空状态
        return;
    }

    if (activeView === 'overview') {
        renderOverview(container);
    } else if (isCategoryView(activeView)) {
        // 一级分类视图
        renderCategoryView(container, activeView);
    } else {
        // 单项分析器视图
        renderAnalyzerDetail(container, activeView);
    }
}

/**
 * 渲染总览仪表盘
 */
function renderOverview(container) {
    const summary = currentResults.summary;
    const results = currentResults.results;
    const highRiskCount = results.filter(r => r.level === 'danger').length;
    const mediumRiskCount = results.filter(r => r.level === 'warning').length;

    container.innerHTML = `
        <div style="padding: 0 20px;">
            <!-- 顶部概览卡片 -->
            <div style="display:grid; grid-template-columns: repeat(4, 1fr); gap:20px; margin-bottom:30px;">
                <div style="background:white; padding:20px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05);">
                    <div style="color:#909399; font-size:14px;">分析对象</div>
                    <div style="font-size:24px; font-weight:bold; color:#303133; margin-top:10px;">${currentResults.subjectName}</div>
                </div>
                <div style="background:white; padding:20px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05);">
                    <div style="color:#909399; font-size:14px;">高风险项</div>
                    <div style="font-size:24px; font-weight:bold; color:#f56c6c; margin-top:10px;">${highRiskCount} <span style="font-size:14px;">项</span></div>
                </div>
                <div style="background:white; padding:20px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05);">
                    <div style="color:#909399; font-size:14px;">中风险项</div>
                    <div style="font-size:24px; font-weight:bold; color:#e6a23c; margin-top:10px;">${mediumRiskCount} <span style="font-size:14px;">项</span></div>
                </div>
                <div style="background:white; padding:20px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05);">
                    <div style="color:#909399; font-size:14px;">分析时间</div>
                    <div style="font-size:16px; font-weight:bold; color:#606266; margin-top:15px;">${new Date(currentResults.completedAt).toLocaleTimeString()}</div>
                </div>
            </div>

            <!-- 异常检测汇总 -->
            <div style="background:white; padding:25px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05); margin-bottom:30px;">
                <h3 style="margin:0 0 20px;">📊 异常检测汇总</h3>
                <div style="display:grid; grid-template-columns: repeat(2, 1fr); gap:20px;">
                    ${renderCategorySummary('financial', '资金战法')}
                    ${renderCategorySummary('communication', '通讯战法')}
                    ${renderCategorySummary('geospatial', '轨迹战法')}
                    ${renderCategorySummary('correlation', '综合关联')}
                </div>
            </div>
        </div>
    `;
}

/**
 * 渲染分类汇总卡片
 */
function renderCategorySummary(groupId, title) {
    const group = ANALYZER_GROUPS.find(g => g.id === groupId);
    const groupResults = currentResults.results.filter(r =>
        group.analyzers.some(a => a.id === r.type)
    );

    const findings = groupResults.filter(r => r.count > 0);

    return `
        <div style="border:1px solid #ebeef5; border-radius:4px; padding:15px;">
            <div style="display:flex; justify-content:space-between; margin-bottom:15px;">
                <strong>${group.icon} ${title}</strong>
                <span style="color:#909399; font-size:12px;">${findings.length}/${group.analyzers.length} 异常</span>
            </div>
            ${findings.length === 0 ? '<div style="color:#c0c4cc; font-size:13px; text-align:center; padding:10px;">✓ 未发现异常</div>' : ''}
            <div style="display:flex; flex-direction:column; gap:10px;">
                ${findings.map(r => `
                    <div onclick="window.AnalysisModule.switchView('${r.type}')" 
                         style="display:flex; justify-content:space-between; font-size:13px; cursor:pointer; padding:8px; background:#f5f7fa; border-radius:4px; hover:background:#ecf5ff;">
                        <span>${r.title}</span>
                        <span style="color:${r.level === 'danger' ? '#f56c6c' : '#e6a23c'}; font-weight:bold;">${r.count} 条</span>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

/**
 * 判断是否为分类视图（一级分类）
 */
function isCategoryView(viewId) {
    return ANALYZER_GROUPS.some(g => g.id === viewId);
}

/**
 * 渲染分类汇总视图
 */
function renderCategoryView(container, categoryId) {
    const category = ANALYZER_GROUPS.find(g => g.id === categoryId);

    if (!category) {
        container.innerHTML = '<div style="padding:40px; text-align:center;">未找到该分类</div>';
        return;
    }

    // 获取该分类下的所有分析结果
    const categoryResults = currentResults.results.filter(r =>
        category.analyzers.some(a => a.id === r.type)
    );

    const findings = categoryResults.filter(r => r.count > 0);
    const totalFindings = findings.reduce((sum, r) => sum + r.count, 0);
    const highRiskCount = findings.filter(r => r.level === 'danger').length;
    const mediumRiskCount = findings.filter(r => r.level === 'warning').length;

    container.innerHTML = `
        <div style="background:white; padding:30px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05); min-height:100%;">
            <div style="border-bottom:1px solid #ebeef5; padding-bottom:20px; margin-bottom:30px;">
                <div style="display:flex; align-items:center; gap:15px;">
                    <span style="font-size:48px;">${category.icon}</span>
                    <div>
                        <h2 style="margin:0 0 10px;">${category.title}</h2>
                        <p style="margin:0; color:#606266;">共 ${category.analyzers.length} 项分析模型</p>
                    </div>
                </div>
            </div>

            <!-- 统计卡片 -->
            <div style="display:grid; grid-template-columns: repeat(3, 1fr); gap:20px; margin-bottom:30px;">
                <div style="background:#f0f9ff; padding:20px; border-radius:8px; border-left:4px solid #409eff;">
                    <div style="color:#909399; font-size:14px; margin-bottom:8px;">发现异常</div>
                    <div style="font-size:28px; font-weight:bold; color:#409eff;">${totalFindings}</div>
                    <div style="color:#606266; font-size:12px; margin-top:5px;">${findings.length}/${category.analyzers.length} 项有异常</div>
                </div>
                <div style="background:#fef0f0; padding:20px; border-radius:8px; border-left:4px solid #f56c6c;">
                    <div style="color:#909399; font-size:14px; margin-bottom:8px;">高风险项</div>
                    <div style="font-size:28px; font-weight:bold; color:#f56c6c;">${highRiskCount}</div>
                    <div style="color:#606266; font-size:12px; margin-top:5px;">需要重点关注</div>
                </div>
                <div style="background:#fdf6ec; padding:20px; border-radius:8px; border-left:4px solid #e6a23c;">
                    <div style="color:#909399; font-size:14px; margin-bottom:8px;">中风险项</div>
                    <div style="font-size:28px; font-weight:bold; color:#e6a23c;">${mediumRiskCount}</div>
                    <div style="color:#606266; font-size:12px; margin-top:5px;">需要关注</div>
                </div>
            </div>

            <!-- 分析结果列表 -->
            <div>
                <h3 style="margin:0 0 20px; font-size:16px; color:#303133;">📋 详细结果</h3>
                ${categoryResults.length === 0 ?
            '<div style="padding:40px; text-align:center; color:#c0c4cc;">暂无分析结果</div>' :
            categoryResults.map(r => {
                const analyzerConfig = findAnalyzerConfig(r.type);
                return `
                            <div onclick="window.AnalysisModule.switchView('${r.type}')" 
                                 style="padding:20px; margin-bottom:15px; background:${r.count > 0 ? '#f5f7fa' : 'white'}; 
                                        border:1px solid ${r.level === 'danger' ? '#f56c6c' : r.level === 'warning' ? '#e6a23c' : '#dcdfe6'}; 
                                        border-radius:8px; cursor:pointer; transition: all 0.2s;"
                                 onmouseover="this.style.boxShadow='0 2px 12px 0 rgba(0,0,0,0.1)'"
                                 onmouseout="this.style.boxShadow='none'">
                                <div style="display:flex; justify-content:space-between; align-items:center;">
                                    <div>
                                        <h4 style="margin:0 0 8px; font-size:15px; color:#303133;">${r.title}</h4>
                                        <p style="margin:0; color:#909399; font-size:13px;">${r.summary}</p>
                                    </div>
                                    <div style="text-align:right;">
                                        ${r.count > 0 ? `
                                            <div style="display:inline-block; padding:6px 12px; border-radius:4px; 
                                                       background:${r.level === 'danger' ? '#f56c6c' : '#e6a23c'}; 
                                                       color:white; font-weight:bold; font-size:14px;">
                                                ${r.count} 条
                                            </div>
                                        ` : `
                                            <div style="color:#67c23a; font-size:14px;">✓ 正常</div>
                                        `}
                                    </div>
                                </div>
                            </div>
                        `;
            }).join('')
        }
            </div>
        </div>
    `;
}

/**
 * 渲染单项分析详情
 */
function renderAnalyzerDetail(container, analyzerId) {
    const result = currentResults.results.find(r => r.type === analyzerId);

    if (!result) {
        container.innerHTML = '<div style="padding:40px; text-align:center;">未找到分析结果</div>';
        return;
    }

    let contentHtml = '';
    const analyzerConfig = findAnalyzerConfig(analyzerId);

    if (analyzerConfig && window[analyzerConfig.class]) {
        const analyzerInstance = new window[analyzerConfig.class]('temp', null);
        contentHtml = analyzerInstance.renderResult(result.data);
    } else {
        contentHtml = '<p>无法渲染详情，请重新分析</p>';
    }

    container.innerHTML = `
        <div style="background:white; padding:30px; border-radius:8px; box-shadow:0 2px 12px 0 rgba(0,0,0,0.05); min-height:100%;">
            <div style="border-bottom:1px solid #ebeef5; padding-bottom:20px; margin-bottom:20px; display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <h2 style="margin:0 0 10px;">${result.title}</h2>
                    <p style="margin:0; color:#606266;">${result.summary}</p>
                </div>
                <div style="text-align:right; display:flex; gap:10px; align-items:center;">
                     <button onclick="window.AnalysisModule.runSingleAnalysis('${analyzerId}')" 
                             style="padding:8px 16px; background:#409eff; color:white; border:none; border-radius:4px; cursor:pointer; font-size:14px;"
                             onmouseover="this.style.background='#66b1ff'"
                             onmouseout="this.style.background='#409eff'">
                         🔄 重新分析
                     </button>
                     <span style="display:inline-block; padding:5px 15px; border-radius:20px; background:${result.level === 'danger' ? '#fef0f0' : '#fdf6ec'}; color:${result.level === 'danger' ? '#f56c6c' : '#e6a23c'}; font-weight:bold;">
                        ${result.count > 0 ? `发现 ${result.count} 条异常` : '正常'}
                     </span>
                </div>
            </div>
            
            <div class="result-detail-content">
                ${contentHtml}
            </div>
        </div>
    `;
}

function findAnalyzerConfig(id) {
    for (const group of ANALYZER_GROUPS) {
        const found = group.analyzers.find(a => a.id === id);
        if (found) return found;
    }
    return null;
}

/**
 * 设置事件监听
 */
function setupEventListeners() {
    const selector = document.getElementById('subject-selector');
    const startBtn = document.getElementById('btn-start-analysis');

    if (selector) {
        selector.addEventListener('change', onSubjectChange);
    }

    if (startBtn) {
        startBtn.addEventListener('click', onStartAnalysis);
    }
}

/**
 * 尝试加载上次的分析结果
 */
async function tryLoadLastResult() {
    const caseId = sessionStorage.getItem('currentCaseId');
    const subjectId = currentSubject ? currentSubject.id : null;

    const hasResult = await window.AnalysisResultService.hasResult(caseId, subjectId);
    if (hasResult) {
        const resultData = await window.AnalysisResultService.loadResult(caseId, subjectId);
        if (resultData && resultData.results) {
            currentResults = resultData.results;
            updateSidebarBadges();
            switchView('overview');
        }
    } else {
        updateSidebarBadges();
        renderContent();
    }
}

/**
 * 更新侧边栏徽章
 */
function updateSidebarBadges() {
    // 先隐藏所有徽章
    document.querySelectorAll('.nav-item .badge').forEach(el => el.style.display = 'none');

    if (!currentResults || !currentResults.results) return;

    currentResults.results.forEach(r => {
        const badge = document.getElementById(`badge-${r.type}`);
        if (badge) {
            if (r.count > 0) {
                badge.style.display = 'inline-block';
                badge.textContent = r.count;
                badge.style.background = r.level === 'danger' ? '#f56c6c' : '#e6a23c';
                badge.style.color = 'white';
            } else {
                badge.style.display = 'none';
            }
        }
    });
}

/**
 * 当选择对象变化时
 */
async function onSubjectChange(event) {
    const subjectId = event.target.value;
    const overviewBar = document.getElementById('subject-overview-bar');

    // 重置结果状态
    currentResults = null;

    if (!subjectId) {
        currentSubject = null;
        overviewBar.style.display = 'none';
    } else {
        currentSubject = allSubjects.find(s => s.id === subjectId);
        if (currentSubject) {
            document.getElementById('overview-name').textContent = currentSubject.name;
            document.getElementById('overview-bank-count').textContent = currentSubject.accounts.bank.length;
            document.getElementById('overview-phone-count').textContent = currentSubject.accounts.phone.length;
            overviewBar.style.display = 'flex';
        }
    }

    await tryLoadLastResult();
}

/**
 * 开始分析
 */
async function onStartAnalysis() {
    const caseId = sessionStorage.getItem('currentCaseId');
    const container = document.getElementById('analysis-content-area');

    // 显示加载状态
    container.innerHTML = `
        <div style="height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center;">
            <div style="font-size:48px; margin-bottom:20px;">⏳</div>
            <h3>正在全方位分析中...</h3>
            <p style="color:#909399;">正在运行 18 个分析模型，请稍候</p>
        </div>
    `;

    try {
        const results = [];

        // 扁平化所有分析器配置
        const allAnalyzers = [];
        ANALYZER_GROUPS.forEach(g => allAnalyzers.push(...g.analyzers));

        for (const config of allAnalyzers) {
            if (!window[config.class]) continue;

            const analyzer = new window[config.class](caseId, currentSubject);
            const result = await analyzer.analyze(config.params);

            // 注入 type 方便后续查找
            result.type = config.id;

            results.push({ analyzer, result });
        }

        // 汇总结果
        const totalFindings = results.reduce((sum, r) => sum + r.result.count, 0);
        const highestLevel = results.some(r => r.result.level === 'danger') ? 'danger'
            : results.some(r => r.result.level === 'warning') ? 'warning' : 'info';

        const saveData = {
            subjectName: currentSubject ? currentSubject.name : '全部数据',
            summary: `完成 ${results.length} 项分析，发现 ${totalFindings} 条异常记录`,
            results: results.map(r => ({
                type: r.result.type,
                title: r.result.title,
                count: r.result.count,
                level: r.result.level,
                summary: r.result.summary,
                data: r.result.data // 保存原始数据以便重新渲染详情页
            })),
            level: highestLevel,
            completedAt: new Date().toISOString()
        };

        // 保存
        await window.AnalysisResultService.saveResult(
            caseId,
            currentSubject ? currentSubject.id : null,
            saveData
        );

        currentResults = saveData;
        updateSidebarBadges();
        switchView('overview');

    } catch (error) {
        console.error('[Analysis] 分析失败:', error);
        container.innerHTML = `
            <div style="height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; color:#f56c6c;">
                <div style="font-size:48px; margin-bottom:20px;">❌</div>
                <h3>分析过程出错</h3>
                <p>${error.message}</p>
            </div>
        `;
    }
}

/**
 * 运行单项分析
 */
async function runSingleAnalysis(analyzerId) {
    const caseId = sessionStorage.getItem('currentCaseId');
    const analyzerConfig = findAnalyzerConfig(analyzerId);

    if (!analyzerConfig || !window[analyzerConfig.class]) {
        alert('未找到对应的分析器');
        return;
    }

    const container = document.getElementById('analysis-content-area');

    // 显示加载状态
    container.innerHTML = `
        <div style="height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center;">
            <div style="font-size:48px; margin-bottom:20px;">⏳</div>
            <h3>正在运行分析...</h3>
            <p style="color:#909399;">${analyzerConfig.name}</p>
        </div>
    `;

    try {
        // 运行单个分析器
        const analyzer = new window[analyzerConfig.class](caseId, currentSubject);
        const result = await analyzer.analyze(analyzerConfig.params);
        result.type = analyzerConfig.id;

        // 如果 currentResults 为空（例如直接点击单项分析），则初始化它
        if (!currentResults) {
            currentResults = {
                subjectName: currentSubject ? currentSubject.name : '全部数据',
                summary: '单项分析结果',
                results: [],
                level: 'info',
                completedAt: new Date().toISOString()
            };
        }

        // 确保 results 数组存在
        if (!currentResults.results) {
            currentResults.results = [];
        }

        // 更新 currentResults 中的这一项
        const index = currentResults.results.findIndex(r => r.type === analyzerId);
        if (index !== -1) {
            currentResults.results[index] = {
                type: result.type,
                title: result.title,
                count: result.count,
                level: result.level,
                summary: result.summary,
                data: result.data
            };
        } else {
            // 如果不存在，则添加
            currentResults.results.push({
                type: result.type,
                title: result.title,
                count: result.count,
                level: result.level,
                summary: result.summary,
                data: result.data
            });
        }

        // 重新计算总体风险等级和摘要
        const totalFindings = currentResults.results.reduce((sum, r) => sum + r.count, 0);
        currentResults.level = currentResults.results.some(r => r.level === 'danger') ? 'danger'
            : currentResults.results.some(r => r.level === 'warning') ? 'warning' : 'info';
        currentResults.summary = `完成 ${currentResults.results.length} 项分析，发现 ${totalFindings} 条异常记录`;
        currentResults.completedAt = new Date().toISOString();

        // 保存更新后的结果
        await window.AnalysisResultService.saveResult(
            caseId,
            currentSubject ? currentSubject.id : null,
            currentResults
        );

        // 刷新界面
        updateSidebarBadges();
        renderAnalyzerDetail(container, analyzerId);

    } catch (error) {
        console.error('[Analysis] 单项分析失败:', error);
        container.innerHTML = `
            <div style="height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; color:#f56c6c;">
                <div style="font-size:48px; margin-bottom:20px;">❌</div>
                <h3>分析过程出错</h3>
                <p>${error.message}</p>
            </div>
        `;
    }
}

// 暴露到全局
window.AnalysisModule = {
    openAnalysisTab,
    switchView,
    runSingleAnalysis,
    initializeAnalysisModule: () => {
        console.log('[Analysis] 智能分析模块已初始化（侧边栏布局版）');
    }
};
